<?php
/**
 * PublicController.class.php
 * 公共控制器
 *
 * @author  王中艺
 * @date    2016-11-15
 */

namespace Wechat\Controller;
use Common\Util\SmsCode;
use Think\Controller;

class PublicController extends BaseController{

    /**
     * 生成微信JsSdk参数
     * @return  json
     */
    function createWxJsSdk(){
        $this->unEmptyParam(array('url'));
        $jsTicket   = $this->wechat->getJsTicket();
        if($jsTicket === false)
            $this->outOInfo($this->wechat->errCode.':'.$this->wechat->errMsg, 0);
        
        $nonceStr   = date('YmdHis').rand(1111, 9999);
        $timestamp  = time();
        $url    = base64_decode(I('get.url'));

        $signStr    = sprintf(
            "jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s",
            $jsTicket,
            $nonceStr,
            $timestamp,
            $url
        );
        $signature  = sha1($signStr);

        $info   = array(
            'app_id'    => C('wechat.app_id'),
            'timestamp' => $timestamp,
            'nonce_str' => $nonceStr,
            'signature' => $signature,
            'js_ticket' => $jsTicket,
            'url'   => $url,
            'sign_str'  => $signStr
        );

        $this->outOInfo($info);
    }

    /**
     * 微信js支付测试接口
     * @return [type] [description]
     */
    function wxPayTest(){
        $wxPay  = new \Wechat\Util\WxPay();
        $tradeNo    = date('YmdHis').rand(1111, 9999);
        $payInfo    = $wxPay->createJsPay(1101, '测试商品', $tradeNo, 1, 'oppWquM3PtK0qx-IDc0fjFp6b88k');
        
        if($payInfo === false)
            $this->outOInfo('订单发起失败!', 0);

        $this->outOInfo($payInfo);
    }

    /**
     * 微信支付回掉
     * @param   I('path.2') 加密支付ID
     * @return  json
     */
    function wxPayNotify(){
        $payId  = think_decrypt(I('path.2'));
        $dMoney     = D('Money');
        $result     = $dMoney->successPay($payId);
        if($result === false)
            $this->outOInfo($dMoney->errMsg, 0);
        
        echo 'SUCCESS';
    }

    /**
     * 微信扫码支付回调
     * @param   xml 支付信息
     * @return  unknown
     */
    function wxScanPayNotify(){
        $orderInfo  = simplexml_load_string(
            file_get_contents('php://input'), 
            'SimpleXMLElement', 
            LIBXML_NOCDATA
        );
        $orderInfo  = json_decode(json_encode($orderInfo), true);
        $response   = [
            'return_code'   => 'SUCCESS',
            'appid' => $orderInfo['appid'],
            'mch_id'    => $orderInfo['mch_id'],
            'nonce_str' => $orderInfo['nonce_str']
        ];

        $WxPay  = new \Wechat\Util\WxPay();
        $model  = new \Think\Model();
        $model->startTrans();
        try{
            //用户信息获取
            $userInfo   = D('User')->getUserInfo($orderInfo['openid']);
            if(!$userInfo){
                //未找到用户则从服务端获取
                $Wechat     = \Wechat\Util\WechatExt::getInstance();
                $userInfo   = $Wechat->getUserInfo($orderInfo['openid']);
                //将信息添加至本地
                $userInfo['id']    = D('User')->addUser($userInfo);
                //注册用户关系连信息
                D('User')->addUserRelaInfo($userInfo['id'], [
                    'dean_id'   => -1,
                    'expand_id' => -1,
                    'teacher_id'    => -1,
                    'parent_id' => 0
                ]);
            }
            $userId     = $userInfo['id'];

            //商品信息分析
            $goodsType  = floor((int)$orderInfo['product_id']/10000);
            $goodsId    = (int)$orderInfo['product_id']%10000;
            switch($goodsType){
                case 5:
                    $goodsInfo  = C('VIP_TYPE.'.$goodsId);
                    $goodsAmount     = $goodsInfo['amount'];
                    $goodsName  = '豆宝电台VIP'.$goodsInfo['date_desc'];
                break;
                default:
                    throw new \Exception('该商品无法支付购买');
                break;
            }
            //支付信息写入数据表
            $remark     = json_encode(['action' => '购买', 'goods_name'   => $goodsName]);
            $payCate    = 2;
            $moneyInfo  = D('Money')->createPay($userId, $goodsType, $goodsId, $goodsAmount, $remark, $payCate);

            //调用微信下单接口
            $payInfo    = $WxPay->createPay(
                $moneyInfo['id'], 
                $goodsName, 
                $moneyInfo['trade_no'],
                $goodsAmount * 100,
                $orderInfo['openid'],
                'NATIVE'
            );
            $model->commit();
            $response['result_code']    = 'SUCCESS';
            $response['prepay_id']  = $payInfo['prepay_id'];
        }catch(\Exception $e){
            $model->rollback();
            $response['result_code']    = 'FAIL';
            $response['err_code_des']   = $e->getMessage();
        }
        $response['sign']   = $WxPay->createSign($response);
        echo arr2xml($response);
        exit;
    }

    /**
     * 发送验证码
     * @param   $username
     * @return  boolean
     */
    function sendVerifyCode(){
        $this->unEmptyParam['username'];
        $username   = $this->iInfo['username'];
        $code     = SmsCode::send($username);
        $this->outOInfo('Oh yes!');
    }

    /**
     * 文件上传功能
     * @param   $_FILES
     * @return  $fileInfo
     */
    function upload(){
        if(empty($_FILES))
            $this->outOInfo('File not find!', 0);

        $upload = new \Think\Upload();
        $upload->rootPath  =     'Uploads/';

        $fileInfo   =   $upload->upload();
        if(!$fileInfo)
            $this->outOInfo($upload->getError(), 0);

        $file   = [
            'src'   => C('SERVER_NAME').'/server/Uploads/'.$fileInfo['Filedata']['savepath'].
                $fileInfo['Filedata']['savename'],
            'info'  => $fileInfo['Filedata']
        ];

        //根据类型返回对应信息
        $type   = $this->iInfo['type'];
        switch($type){
            case 'wangeditor':
                echo $file['src'];
                exit;
            break;
            default:
                $this->outOInfo(['file' => $file]);
            break; 
        }
            
    }

    function debug(){
        create_2d_code('https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx700a7445d2a5f94e&redirect_uri=http%3A%2F%2Fheart.iruiyou.com%2Fwechat%2Fhtml%2Findex.html%3F%23%2FVip%2Fpurchase&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect');
    }
}
